package com.lframework.xingyun.sc.service.army;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lframework.xingyun.basedata.entity.ArmyProductInfo;
import com.lframework.xingyun.basedata.entity.ArmySaleOrder;
import com.lframework.xingyun.basedata.service.IArmyProductInfoService;
import com.lframework.xingyun.basedata.service.IArmySaleOrderService;
import com.lframework.xingyun.core.poi.EasyExcelUtil;
import com.lframework.xingyun.core.poi.ExcelFile;
import com.lframework.xingyun.core.poi.SheetInfoBean;
import com.lframework.xingyun.core.poi.SheetInfoBeanNoModel;
import com.lframework.xingyun.sc.entity.ArmySaleOrderDaDuiVO;
import com.lframework.xingyun.sc.entity.ArmySaleOrderVO;
import com.lframework.xingyun.sc.entity.ArmySaleOrderAllVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BillExportService {

    private static List<String> MEET_LIST_TYPE = Lists.newArrayList("鸡肉", "牛肉", "猪肉", "米线");

    @Autowired
    private IArmySaleOrderService iArmySaleOrderService;
    @Autowired
    private IArmyProductInfoService iArmyProductInfoService;

    public void exportFenDan(String ds, HttpServletResponse response) {
        Map<String, Map<String, List<ArmySaleOrder>>> orderMap = iArmySaleOrderService.selectByDs(ds, null).stream()
                .collect(Collectors.groupingBy(ArmySaleOrder::getCustomer,
                        Collectors.groupingBy(ArmySaleOrder::getSubCustomer)));

        List<ExcelFile> excelFileList = Lists.newArrayList();
        orderMap.forEach((customer, subCustomerMap) -> {
            excelFileList.add(new ExcelFile(customer + "-" + ds, getSubCustomerSheetList(ds, subCustomerMap), null));
        });

        EasyExcelUtil.exportZip(ds + "-分队汇总", excelFileList, response);
    }

    /**
     * 分队
     *
     * @param subCustomerMap
     * @return
     */
    private static List<SheetInfoBean> getCustomerSheetList(String ds, Map<String, List<ArmySaleOrderAllVO>> subCustomerMap) {
        List<SheetInfoBean> sheetInfoList = new ArrayList<>();
        List<Map.Entry<String, List<ArmySaleOrderAllVO>>> subCustomerEntry = Lists.newArrayList(subCustomerMap.entrySet());
        for (int i = 0; i < subCustomerEntry.size(); i++) {
            Map.Entry<String, List<ArmySaleOrderAllVO>> entry = subCustomerEntry.get(i);
            SheetInfoBean<ArmySaleOrderDaDuiVO> sheetInfo = new SheetInfoBean();
            sheetInfo.setSheetIndex(i);
            sheetInfo.setSheetName(entry.getKey());
            sheetInfo.setHeadClass(ArmySaleOrderDaDuiVO.class);

            List<ArmySaleOrderDaDuiVO> data = ArmyConverter.convertOrderDaDuiVOList(entry.getValue());

            sheetInfo.setDataList(data);
            sheetInfoList.add(sheetInfo);
        }
        return sheetInfoList;
    }

    /**
     * 分队
     *
     * @param subCustomerMap
     * @return
     */
    private static List<SheetInfoBean> getSubCustomerSheetList(String ds, Map<String, List<ArmySaleOrder>> subCustomerMap) {
        List<SheetInfoBean> sheetInfoList = new ArrayList<>();
        List<Map.Entry<String, List<ArmySaleOrder>>> subCustomerEntry = Lists.newArrayList(subCustomerMap.entrySet());
        for (int i = 0; i < subCustomerEntry.size(); i++) {
            Map.Entry<String, List<ArmySaleOrder>> entry = subCustomerEntry.get(i);
            SheetInfoBean<ArmySaleOrderVO> sheetInfo = new SheetInfoBean();
            sheetInfo.setSheetIndex(i);
            sheetInfo.setSheetName(entry.getKey());
            sheetInfo.setHeadClass(ArmySaleOrderVO.class);

            List<ArmySaleOrderVO> data = ArmyConverter.convertOrderVOList(ds, entry.getKey(), entry.getValue());

            sheetInfo.setDataList(data);
            sheetInfoList.add(sheetInfo);
        }
        return sheetInfoList;
    }

    public void export(String ds, String customerName, HttpServletResponse response) {
        List<ArmySaleOrder> orderList = iArmySaleOrderService.selectByDs(ds, customerName);
        List<ArmySaleOrderVO> data = ArmyConverter.convertOrderVOList(ds, customerName, orderList);

        EasyExcelUtil.exportExcel(data, ArmySaleOrderVO.class, customerName, response);
    }


    public void exportDaDui(String ds, HttpServletResponse response) {
        Map<String, List<ArmySaleOrderAllVO>> orderMap = getOrderAllVOS(ds).stream()
                .collect(Collectors.groupingBy(ArmySaleOrderAllVO::getCustomer));

        List<ExcelFile> excelFileList = Lists.newArrayList();
        orderMap.forEach((customer, list) -> {
            Map<String, List<ArmySaleOrderAllVO>> subCustomerMap = Maps.newHashMap();
            subCustomerMap.put(customer, list);

            excelFileList.add(new ExcelFile(customer + "-" + ds, getCustomerSheetList(ds, subCustomerMap), null));
        });

        EasyExcelUtil.exportZip(ds + "-大队汇总", excelFileList, response);
    }

    public void exportRouLei(String ds, HttpServletResponse response) {
        List<ArmySaleOrderAllVO> orderAllVOList = getOrderAllVOS(ds).stream()
                .filter(item -> StringUtils.isNotBlank(item.getSubType()))
                .collect(Collectors.toList());

        List<ExcelFile> excelFileList = Lists.newArrayList();
        MEET_LIST_TYPE.forEach(subType -> {
            List<ArmySaleOrderAllVO> list = orderAllVOList.stream().filter(item -> item.getSubType().equals(subType)).collect(Collectors.toList());
            // head
            List<String> customerList = list.stream().map(item -> item.getCustomer() + "-" + item.getSubCustomer()).distinct().collect(Collectors.toList());
            // 每个单品统计
            List<List<String>> dataList = getDataList(list, customerList);
            SheetInfoBeanNoModel infoBeanNoModel = new SheetInfoBeanNoModel();
            infoBeanNoModel.setSheetName(subType);
            infoBeanNoModel.setSheetIndex(0);

            List<String> headerList = Lists.newArrayList("品名");
            headerList.addAll(customerList);
            infoBeanNoModel.setHeadList(headerList);
            infoBeanNoModel.setDataList(dataList);

            excelFileList.add(new ExcelFile(subType + "-" + ds, null, Lists.newArrayList(infoBeanNoModel)));
        });

        EasyExcelUtil.exportZipNoModel(ds + "-肉类米线汇总", excelFileList, response);
    }

    private static List<List<String>> getDataList(List<ArmySaleOrderAllVO> list, List<String> headList) {
        List<List<String>> dataList = Lists.newArrayList();
        list.stream().collect(Collectors.groupingBy(ArmySaleOrderAllVO::getProductName))
                .forEach((key, value) -> {
                    List<String> rowList = Lists.newArrayList();
                    rowList.add(key);
                    // 单用户的产品
                    Map<String, List<ArmySaleOrderAllVO>> customerMap = value.stream().collect(Collectors.groupingBy(item -> String.format("%s-%s", item.getCustomer(), item.getSubCustomer())));
                    headList.forEach(customer -> {
                        List<ArmySaleOrderAllVO> customerProductList = customerMap.get(customer);
                        if (CollectionUtils.isEmpty(customerProductList)) {
                            rowList.add("0");
                        } else {
                            rowList.add(customerProductList.stream().mapToDouble(ArmySaleOrderAllVO::getNum).sum() + "");
                        }
                    });
                    dataList.add(rowList);
                });
        return dataList;
    }

    /**
     * 获取订单的全量信息
     *
     * @param ds
     * @return
     */
    private List<ArmySaleOrderAllVO> getOrderAllVOS(String ds) {
        Map<String, List<ArmyProductInfo>> productMap = iArmyProductInfoService.selectAll().stream()
                .collect(Collectors.groupingBy(item -> item.getName() + "#" + item.getUnit()));

        // 全量信息
        List<ArmySaleOrderAllVO> orderAllVOList = iArmySaleOrderService.selectByDs(ds, null).stream()
                .map(item -> {
                    List<ArmyProductInfo> productInfoList = productMap.get(String.format("%s#%s", item.getProductName(), item.getUnit()));
                    ArmyProductInfo productInfo = productInfoList == null ? new ArmyProductInfo() : productInfoList.get(0);

                    ArmySaleOrderAllVO allVO = new ArmySaleOrderAllVO();
                    allVO.setSubCustomer(item.getSubCustomer());
                    allVO.setPrice(productInfo.getPrice());
                    allVO.setType(productInfo.getType());
                    allVO.setSubType(productInfo.getSubType());
                    allVO.setTaxRate(productInfo.getTaxRate());
                    allVO.setDs(ds);
                    allVO.setCustomer(item.getCustomer());
                    allVO.setProductName(item.getProductName());
                    allVO.setNum(item.getNum().doubleValue());
                    allVO.setUnit(item.getUnit());
                    return allVO;
                })
                .sorted(Comparator.comparing(ArmySaleOrderAllVO::getCustomer)
                        .thenComparing(ArmySaleOrderAllVO::getSubCustomer, Comparator.nullsFirst(String::compareTo)))
                .collect(Collectors.toList());
        return orderAllVOList;
    }
}
